package hhm.framessm.authority.service.impl;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidDataSource;

import hhm.framessm.authority.service.UserService;
import hhm.framessm.pojo.TbRole;
import hhm.framessm.pojo.TbUser;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private DruidDataSource dataSource;

	@Override
	public void insertUser(TbUser user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateUser(TbUser user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deleteUser(String id) {
		// TODO Auto-generated method stub

	}

	@Override
	public TbUser findUserById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TbUser> findAllUser() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TbUser login(String username, String password) {
		TbUser user = null;
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "select user_id,user_name,user_pwd from tb_user where user_name=? and user_pwd=?";
		Object[] params = { username, password };
		try {
			user = (TbUser) runner.query(sql, new BeanHandler(TbUser.class), params);
			if (user != null) {
				sql = "select r.role_id,r.role_name,r.description from tb_role r, tb_user_role ur where r.role_id=ur.role_id and ur.user_id=?";
				params = new Object[] { user.getUserId() };
				Set<TbRole> set = new HashSet<TbRole>();
				set.addAll((List<TbRole>) runner.query(sql, new BeanListHandler(TbRole.class), params));
				user.setRoles(set);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return user;
	}

}
